package wfl.spec.edu;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ActivitySecond extends AppCompatActivity implements NetListViewUtils.LoadListener  {
    private NetListViewUtils listViewUtils;
    private List<String> list = new ArrayList<>();
    private ArrayAdapter<String> adapter;
    int a = 0;
    private static final String TAG = "ActivitySecond";
    List<Message> messageList = null;
//    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        sendRequestWihtOkhttp();
        // 初始化数据
        //addList();
        // 获取控件
        Init();
        // 适配器加载数据
        adapter = new ArrayAdapter<>(ActivitySecond.this,android.R.layout.simple_expandable_list_item_1, list);
        listViewUtils.setAdapter(adapter);
        sendRequestWihtOkhttp();
//        // 构造Adapter
//        MessageAdapter fa = new MessageAdapter(ActivitySecond.this, R.layout.layout_fruit_item, messageList);
//        // 找到ListView
//        ListView lv = (ListView)findViewById(R.id.imageLV);
//        // 将Adapter应用到ListView
//        lv.setAdapter(fa);
    }


    /**
     * 发起网络请求
     */
    private void sendRequestWihtOkhttp(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 构造客户端，相当于浏览器
                    OkHttpClient client = new OkHttpClient();
                    // 构造请求，相当于在浏览器里输入地址
                    Request request = new Request
                            .Builder()
                            .url("http://www.yyjsx.xyz/api/message/find?messageCategory=WECHAT&start="+a)
                            .build();
                    // 发送请求，相当于在浏览器按回车
                    Response response = client.newCall(request).execute();
                    // 更新ListView
                    String body = response.body().string();
//                    Log.d(TAG, body);
                    parseJson(body);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void parseJson(String jsonStr){
        try {
            JSONObject jobj = new JSONObject(jsonStr);
            String dataStr = jobj.getString("data");

            Gson gson = new Gson();
            messageList = gson.fromJson(dataStr, new TypeToken<List<Message>>(){}.getType());
            // 更新UI
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    MessageAdapter messageAdapter = new MessageAdapter(ActivitySecond.this, R.layout.fruit_item, messageList);
                    ListView lv = (ListView)findViewById(R.id.list_view);
                    lv.setAdapter(messageAdapter);

                }
            });
            for (Message m : messageList){
                Log.d(TAG,m.getPreview());
                Log.d(TAG, m.getTitle());
                Log.d(TAG, m.getSummary());
                //Log.d("ActivitySecond ","id is"+m.getTitle());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //上拉下拉
    private void Init() {
        listViewUtils = (NetListViewUtils) findViewById(R.id.list_view);
        listViewUtils.setInteface(this);
    }
    //这是上拉刷新添加的数据
    @Override
    public void onLoad() {
        // 设置延时三秒获取时局，用于显示加载效果
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // 这里处理请求返回的结果（这里使用模拟数据）
                // 更新数据
                adapter.notifyDataSetChanged();
                // 加载完毕
                listViewUtils.loadComplete();
            }
        }, 3000);
    }
    //这是下拉刷新添加的数据
    @Override
    public void PullLoad() {
        // 设置延时三秒获取时局，用于显示加载效果
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // 这里处理请求返回的结果（这里使用模拟数据）
                a +=10;
                sendRequestWihtOkhttp();
                //wechatList.add("这是上拉刷新添加的数据");
                // 更新数据
                adapter.notifyDataSetChanged();
                // 加载完毕
                listViewUtils.loadComplete();
            }
        }, 3000);
    }
}